package com.arrogames.rgblabyrinth.game {
	import com.arrogames.tmx.CoordinateUtil;
	import com.arrogames.tmx.StarlingMap;
	
	import flash.geom.Point;
	
	import net.pixelpracht.tmx.TmxObject;
	import net.pixelpracht.tmx.TmxObjectGroup;

	public class LevelLoader {
		
		[Embed(source="/assets/maps/tiles.png")] 
		private var ImgMap:Class;
		[Embed(source="/assets/maps/level0.tmx", mimeType="application/octet-stream")] 
		private var TmxMapData:Class;
		
		private var creator:EntityCreator;
		
		private var halfMapWidth:int;
		private var _map:StarlingMap;
		
		public function LevelLoader(creator:EntityCreator) {
			this.creator = creator;
			loadTmxFile();
		}
		
		private function loadTmxFile():void {
			var xml:XML = new XML(new TmxMapData());
			map = new StarlingMap(xml);
			map.addTileSetTexture("tiles", ImgMap);
			map.createTiledLayers();
		}
		
		public function loadObjectsTmx():void {
			//create the implementation of the objects specified in the ObjectGroup 'objects'
			var tileWidth:Number = map.tileWidth;
			var tileHeight:Number = map.tileHeight;
			var group:TmxObjectGroup = map.getObjectGroup('setup');
			if (group != null) {
				for each(var object:TmxObject in group.objects) {
					var isoCoords:Point = CoordinateUtil.isoScreenToIso(object.x, object.y, tileWidth, tileHeight);
					isoCoords.x = Math.floor(isoCoords.x);
					isoCoords.y = Math.floor(isoCoords.y);
					if (object.name === "start") {
						creator.createPlayer(isoCoords.x, isoCoords.y, tileWidth, tileHeight);
						creator.createStart(isoCoords.x, isoCoords.y, tileWidth, tileHeight);
					} else if (object.name === "end") {
						creator.createExit(isoCoords.x, isoCoords.y, tileWidth, tileHeight);
					} else if (object.name === "bonus") {
						creator.createBonus(isoCoords.x, isoCoords.y, tileWidth, tileHeight);
					}
				}
			}
		}
		
		public function get map():StarlingMap {
			return _map;
		}

		public function set map(value:StarlingMap):void {
			_map = value;
		}


	}
}